import { AdManager } from "./ads/AdManager";
import { BUNDLE_TYPE_ENUM, EVENT_NAME_ENUM } from "./base/EnumIndex";
import { ActionTools } from "./common/ActionTools";
import { Tools } from "./common/Tools";
import LevelPre_Common from "./LevelPre_Common";
import LvItem from "./LvItem";
import { AudioManager1 } from "./manager/AudioManager1";
import { EventManager } from "./manager/EventManager";
import { LevelManager } from "./manager/LevelManager";
import { ResManager1 } from "./manager/ResManager1";
import { UIManager } from "./manager/UIManager";
import { AudioInfo, TweenInfo } from "./model/OtherModel";

const { ccclass, property } = cc._decorator;
/** 关卡父类 */
@ccclass
export default abstract class LevelBase extends cc.Component {
    touchStartPos: cc.Vec3 = null;   //触摸开始坐标
    /** 交互配置 */
    interJson: any = null;

    blockPanel: cc.Node = null;    //黑色幕布

    timeStart: boolean = false;
    onLoad() {
        AudioManager1.stopAllAudio();
        this.addInitListener();
        this.initOnLoad();
    }

    // 子类必须实现此方法
    public abstract init(huaPre: cc.Prefab): void;
    // public abstract getHuaPreParent(): cc.Node;

    async initOnLoad() {
        /** 加载本关Json */
        await ResManager1.ins.loadLevelBundle(LevelManager.ins.getBundleName());
        let jsonAsset = await ResManager1.ins.loadRes("LvJson", cc.JsonAsset, BUNDLE_TYPE_ENUM.LEVEL);
        this.interJson = jsonAsset.json;
        let huaPre = await ResManager1.ins.loadRes("huaPre", cc.Prefab, BUNDLE_TYPE_ENUM.LEVEL);
        let levelPreCommon = await UIManager.ins.createLevelPreCommon();
        levelPreCommon.getComponent(LevelPre_Common).init(this.interJson);
        this.init(huaPre);

        UIManager.ins.closeLoading();// 界面全部准备完毕 关闭loading
        // AudioManager.playAudio("jinruguanka", 1);

        LevelManager.ins.curKeyInfo = this.interJson.keyInfo;

        if (this.interJson.bgm) {
            this.switchBgm(this.interJson.bgm.resUrl, this.interJson.bgm.value);
        }

        AdManager.startVideoScreen();

        if (this.interJson.isKB) {
            let isHideKb = Tools.getStorage('setKbTipActive');
            if (isHideKb && isHideKb != "false") {
                this.initAllItem();
            }else{
                UIManager.ins.showPop("TipUI_KB", BUNDLE_TYPE_ENUM.GAME, this);
            }

        } else {
            this.initAllItem();
        }

        this.node.on(cc.Node.EventType.TOUCH_START, this.touchStart, this, true);
        let idx = LevelManager.ins.getLvInfoIdx(LevelManager.ins.curLvInfo.type, LevelManager.ins.curLvInfo.lv) + 1;
        AdManager.reportLevel(idx, LevelManager.ins.curLvInfo.name, 0);
    };

    touchStart() {
        EventManager.ins.emit(EVENT_NAME_ENUM.START_TIME);
        EventManager.ins.emit(EVENT_NAME_ENUM.RESET_GUIDE_TIP_TIME);
    }


    /** 初始化所有Item */
    private initAllItem() {
        // 初始化所有的LvItem
        let lvComs = this.node.getComponentsInChildren(LvItem);
        for (let i = 0; i < lvComs.length; i++) {
            if (!lvComs[i].levelBase) {
                lvComs[i].initItem(this);
            }
        }
        if (this.interJson.InitArr) {
            for (let i = 0; i < this.interJson.InitArr.length; i++) {
                let data = this.interJson.InitArr[i];
                let node = this.getNodeForName(data.node);
                if (!node) { continue; }
                if (!node.getComponent(LvItem)) {
                    node.addComponent(LvItem);
                }
                node.getComponent(LvItem).initItem(this);
                node.getComponent(LvItem).initItemInfo(data);
            }
        }
        if (this.interJson.InterArr) {
            for (let i = 0; i < this.interJson.InterArr.length; i++) {
                let data = this.interJson.InterArr[i];
                let node = this.getNodeForName(data.node);
                if (!node) { continue; }
                if (!node.getComponent(LvItem)) {
                    node.addComponent(LvItem);
                }
                node.getComponent(LvItem).initItem(this);
                node.getComponent(LvItem).initInterItem(data);
            }
        }
    };
    /** 根据配置信息执行节点的Tween */
    runNodeTween(node: cc.Node, infos: Array<TweenInfo>) {
        if (!node) {
            cc.log(infos)
            return
        }

        if (!node.getComponent(LvItem)) {
            node.addComponent(LvItem).initItem(this);
        }
        node.getComponent(LvItem).runTweenInfo(infos);
    };
    /** 根据配置信息执行节点的Tween */
    runNodeTweenEvent(node: string, info: string) {
        this.runNodeTween(this.getNodeForName(node), this.getInterTwForName(info).interTween);
    };
    /** 执行节点下其他节点的Tween */
    runOtherTween(info: TweenInfo) {
        let node = this.getNodeForName(info.node);
        if (!node) {
            return console.error("找不到节点：" + info.node);
        }
        if (!node.getComponent(LvItem)) {
            node.addComponent(LvItem).initItem(this);
            // return console.error(node.name + "没有添加LvItem脚本", "json:", info);
        }
        let tw = node.getComponent(LvItem).getTweenForInfo(info);
        tw.call(() => { }).start();
    };
    /** 通过节点名字获取要交互的Tween   type交互类型*/
    getInterTwForName(name: string, type?: string) {
        if (!this.interJson.InterArr) { return null; }
        for (let i = 0; i < this.interJson.InterArr.length; i++) {
            const element = this.interJson.InterArr[i];
            if (element.node == name) {
                if (type && element.interType != type) { continue; };
                return element;
            }
        }
        return null;
    };
    /** 通过节点名字获取 播放动画的名字 */
    getArmtureAni(node: string) {
        return this.getNodeForName(node).getComponent(LvItem).getArmtureAni();
    };
    /** 播放音效 */
    async playAudio(audioInfo: AudioInfo) {
        let audioId = await AudioManager1.playAudio(audioInfo.resUrl, audioInfo.value, BUNDLE_TYPE_ENUM.LEVEL);
        AudioManager1.setAudioLoop(audioId, audioInfo.isRepeat);
        if (audioInfo.bgmValue || audioInfo.bgmValue === 0) {
            /** 设置本关卡的背景音乐音量 */
            AudioManager1.setBgValue(audioInfo.bgmValue);
        }
    };
    /** 切换背景音乐 */
    switchBgm(resUrl: string, value: number = 0.3, time: number = 0) {
        if (time == 0) {
            AudioManager1.playBG(resUrl, value, BUNDLE_TYPE_ENUM.LEVEL);
        } else {
            ActionTools._ins.audioValueTween(AudioManager1.bgAudio, 0, time / 3)
                .target(this.node)
                .call(() => {
                    AudioManager1.playBG(resUrl, 0, BUNDLE_TYPE_ENUM.LEVEL);
                }).delay(time / 3).call(() => {
                    ActionTools._ins.audioValueTween(AudioManager1.bgAudio, value, time / 3).target(this.node).start();
                }).delay(time / 3).start();
        }
    };
    /** 通过名字获取节点 */
    getNodeForName(name: string) {
        // cc.log(name, this.node)
        if (!this.node) return null;
        let nodeArr = this.node.getComponentsInChildren(LvItem);
        for (let i = 0; i < nodeArr.length; i++) {
            if (nodeArr[i].node.name == name) {
                return nodeArr[i].node;
            }
        }
        let node = this.getChildForName(name);
        if (node) {
            return node;
        }
        return null;
    };
    /** 通过名字 获取子节点下的节点 */
    getChildForName(name: string, parentNode?: cc.Node): cc.Node {
        if (!name) { return null; }
        parentNode = parentNode || this.node;

        for (let i = 0; i < parentNode.children.length; i++) {
            const node = parentNode.children[i];
            if (node.name == name) {
                return node;
            }
            if (node.children.length > 0) {
                let temp = this.getChildForName(name, node);
                if (temp) {
                    return temp;
                }
            }
        }
        return null;
    };

    /**当前关卡是否支持复活 */
    getIsAgain() {
        if (this.interJson.InterArr) {
            for (let item of this.interJson.InterArr) {
                if (item.node == "reviveGame") {
                    return true;
                }
            }
            return false;
        }
        return false;
    }

    clickBtnReturn() {
        AudioManager1.playClick();
        UIManager.ins.enabledClick(false);
        AudioManager1.stopAllAudio();
        UIManager.ins.closeAll();
        UIManager.ins.showUI("LevelUI", BUNDLE_TYPE_ENUM.HOME);
    }
    clickBtnTip() {
        AudioManager1.playClick();
        let keyInfo = this.interJson.keyInfo;
        UIManager.ins.showPop("TipUI", BUNDLE_TYPE_ENUM.GAME, keyInfo);
    }
    /** 事件  监听 */
    addInitListener() {
        EventManager.ins.on(EVENT_NAME_ENUM.RUN_OTHER_TWEEN, this.runOtherTween, this);
        EventManager.ins.on(EVENT_NAME_ENUM.RUN_NODE_TWEEN, this.runNodeTweenEvent, this);
        EventManager.ins.on(EVENT_NAME_ENUM.KB_GAME_START, this.initAllItem, this);
    };
    onDestroy() {
        // cc.log("levelBase onDestroy")
        this.node.off(cc.Node.EventType.TOUCH_START, this.touchStart, this, true);
        UIManager.ins.enabledGameClick(true);
        this.offEvent();
    };

    offEvent() {
        EventManager.ins.off(EVENT_NAME_ENUM.RUN_OTHER_TWEEN, this.runOtherTween, this);
        EventManager.ins.off(EVENT_NAME_ENUM.RUN_NODE_TWEEN, this.runNodeTweenEvent, this);
        EventManager.ins.off(EVENT_NAME_ENUM.KB_GAME_START, this.initAllItem, this);
    }
}